import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer';
import { useDispatchSignal } from "@/hooks/useSignal";

interface IBillboardConfig {
    width?: number;
    height?: number;
    content?: string;
    fontSize?: number;
    color?: string;
    backgroundColor?: string;
    borderRadius?: number;
}

class Billboard extends CSS2DObject {
    type = 'Billboard';
    isBillboard = true;
    private config: IBillboardConfig;
    private contentElement: HTMLDivElement;

    constructor(config: IBillboardConfig = {}) {
        const container = document.createElement('div');
        container.style.pointerEvents = 'auto';
        super(container);

        this.config = {
            width: 200,
            height: 100,
            content: '广告牌内容',
            fontSize: 16,
            color: '#ffffff',
            backgroundColor: '#409eff',
            borderRadius: 4,
            ...config
        };

        this.contentElement = document.createElement('div');
        this.contentElement.style.cursor = 'pointer';
        container.appendChild(this.contentElement);

        // 初始化样式
        this.updateConfig(this.config);

        // 添加点击事件
        this.contentElement.addEventListener('click', (event) => {
            event.stopPropagation();
            useDispatchSignal("objectSelected", this, false);
        });
    }

    updateConfig(newConfig: Partial<IBillboardConfig>) {
        Object.assign(this.config, newConfig);

        // 更新样式
        this.contentElement.style.width = `${this.config.width}px`;
        this.contentElement.style.height = `${this.config.height}px`;
        this.contentElement.style.fontSize = `${this.config.fontSize}px`;
        //@ts-ignore
        this.contentElement.style.color = this.config.color;
        //@ts-ignore
        this.contentElement.style.backgroundColor = this.config.backgroundColor;
        this.contentElement.style.borderRadius = `${this.config.borderRadius}px`;
        
        // 基础样式
        this.contentElement.style.display = 'flex';
        this.contentElement.style.alignItems = 'center';
        this.contentElement.style.justifyContent = 'center';
        this.contentElement.style.userSelect = 'none';
        
        // 更新内容
        //@ts-ignore
        this.contentElement.textContent = this.config.content;
    }

    // 用于序列化
    //@ts-ignore
    toJSON(meta?: JSONMeta) {
        const superJSON = super.toJSON(meta).object;
        return {
            metadata: {
                version: 4.6,
                type: 'Object',
                generator: 'Billboard.toJSON'
            },
            object: {
                ...superJSON,
                type: this.type,
                config: this.config
            }
        };
    }

    // 用于反序列化
    static fromJSON(data: any) {
        return new Billboard(data.options);
    }
}

export { Billboard, IBillboardConfig };